﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using Caliburn.Micro;
using OI.Framework;

namespace OI.ViewModels
{
    public sealed class ShareNoticeViewModel : Screen
    {
        public string ShareLink {get; private set;}
        

        public ShareNoticeViewModel(string shareLink)
        {
            ShareLink = shareLink;
            CopyToClipboad();
            DisplayName = "Share your mashup";
        }

        /// <summary>
        /// Gets a value indicating whether this instance has access to the clipboard.
        /// </summary>
        public bool HasClipboard
        {
            get
            {
                if (_HasClipboard == null)
                {
                    object o = System.Windows.Browser.HtmlPage.Window.Eval("(window.clipboardData != null && window.clipboardData.setData != null)");
                    _HasClipboard = (o != null && o is bool && (bool)o);
                }
                return _HasClipboard.Value;
            }
        }
        private bool? _HasClipboard;


        public void CopyToClipboad()
        {
            if (!string.IsNullOrEmpty(ShareLink) && HasClipboard)
            {
                try
                {
                    System.Windows.Browser.HtmlPage.Window.Eval("window.clipboardData.setData('Text', '" + ScrubText(ShareLink) + "')");
                }
                catch (Exception ex)
                {
                    IoC.Get<IShell>().HandleException(ex, "Could not copy link to clipboard");
                }
            }
        }


        private static string ScrubText(string text)
        {
            return text.Replace("\r", @"\r").Replace("\n", @"\n").Replace("'", "' + \"'\" + '");
        }


        public void Close()
        {
            TryClose();
        }
    }
}
